package com.ldr.custom.spring.v3.webmvc;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 设计这个类的主要目的是
 * 1、将一个静态文件变为一个动态文件
 * 2、根据用户传参数不同，产生不同的结果
 * 3、最终输出字符串，交给Response输出
 */
public class GPViewResolver {


    private File templateFile;
    private String viewName;

    public GPViewResolver(String viewName, File templateFile){
        this.viewName = viewName;
        this.templateFile = templateFile;
    }

    public String viewResolver(GPModelAndView modelAndView) throws IOException {

        StringBuffer sb=new StringBuffer();
        //由于可以自由访问文件的任意位置，所以如果需要访问文件的部分内容，RandomAccessFile将是更好的选择。
        RandomAccessFile ra=new RandomAccessFile(this.templateFile,"r");
        String line=null;
        while ((line=ra.readLine())!=null){
            Matcher m = matcher(line);
            while (m.find()){
                for (int i = 0; i <= m.groupCount(); i++) {
                   //要把$中间的这个字符串给取出来
                    String paramName = m.group(i);
                    Object paramValue = modelAndView.getModel().get(paramName);
                    if (paramValue==null)continue;
                    paramValue=new String(paramValue.toString().getBytes("UTF-8"), "ISO-8859-1");
                    line=line.replaceAll("\\$\\{"+paramName+"\\}",paramValue.toString());
                }
            }
            sb.append(line);
        }
        return sb.toString();
    }

    private Matcher matcher(String str){
        Pattern pattern=Pattern.compile("\\$\\{(.+?)\\}",Pattern.CASE_INSENSITIVE);
        Matcher m = pattern.matcher(str);
        return m;
    }

    public File getTemplateFile() {
        return templateFile;
    }

    public void setTemplateFiled(File templateFile) {
        this.templateFile = templateFile;
    }

    public String getViewName() {
        return viewName;
    }

    public void setViewName(String viewName) {
        this.viewName = viewName;
    }


    public static void main(String[] args) {
        String str="    <h1>å¤§å®¶å¥½ï¼\u008Cæ\u0088\u0091æ\u0098¯${name}</h1>";
        Pattern pattern=Pattern.compile("\\$\\{(.+?)\\}",Pattern.CASE_INSENSITIVE);
        Matcher m = pattern.matcher(str);

        while (m.find()) {
            for (int i = 1; i <= m.groupCount(); i++) {
                //要把$中间的这个字符串给取出来
                String paramName = m.group(i);
                System.out.println(paramName);
            }
        }
    }
}

